package com.huc.tools.tools.json;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.List;

/**
 * @Author: 胡成
 * @Version: 0.0.1V
 * @Date: 2018/8/9
 * @Description: json工具类
 **/
public class JsonTools {

    private static ObjectMapper mapper = new ObjectMapper();

    /**
     * @Author: 胡成
     * @Date: 2018/8/9 14:02
     * @Description: object转换json
     **/
    public static String objectToJson(Object data) {
        try {
            return mapper.writeValueAsString(data);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @Author: 胡成
     * @Date: 2018/8/9 14:10
     * @Description: 将json装换对象
     **/
    public static <T> T jsonToPojo(String jsonData, Class<T> beanType) {
        try {
            return mapper.readValue(jsonData, beanType);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @Author: 胡成
     * @Date: 2018/8/9 14:14
     * @Description: 将json转换list
     **/
    public static <T> List<T> jsonToList(String jsonData, Class<T> beanType) {
        try {
            JavaType javaType = mapper.getTypeFactory().constructParametricType(List.class, beanType);
            return mapper.readValue(jsonData, javaType);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
